package com.weijianhuawen.wjblog.jwt.handler;

import ch.qos.logback.classic.spi.LoggerContextVO;
import com.weijianhuawen.wjblog.common.utils.Response;
import com.weijianhuawen.wjblog.jwt.helper.JwtTokenHelper;
import com.weijianhuawen.wjblog.jwt.utils.ResultUtil;
import com.weijianhuawen.wjblog.jwt.vo.LoginRsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description: 登录认证成功处理
 * @date: 2024-10-16 22:48
 */
@Component
@Slf4j
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtTokenHelper jwtTokenHelper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //从authentication中获取用户具体信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        //通过用户名生成token
        String username = userDetails.getUsername();
        String token = jwtTokenHelper.generateToken(username);

        //返回token
        LoginRsVO loginRsVO = LoginRsVO.builder()
                .token(token).build();

        ResultUtil.ok(response, Response.success(loginRsVO));
    }
}
